import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:toolbox/common/common.dart';
import 'package:toolbox/common/sizeConfig.dart';
import 'package:toolbox/manager/hive/hiveHelper.dart';
import 'package:toolbox/models/FetchWebsiteInfoModel.dart';
import 'package:toolbox/models/WebBookmarkModel.dart';
import 'package:toolbox/page/browser/browser_logic.dart';
import 'package:toolbox/page/browser/browser_state.dart';
import 'package:toolbox/page/browser/component/add_homepage_url_dialog.dart';
import 'package:toolbox/page/browser/component/edit_bookmark_dialog.dart';
import 'package:intl/intl.dart';
import '../../../widgets/defaultDialog.dart';


enum ToolsType {
  bookmark('书签'),
  homePage('主页'),
  history('历史记录');

  final String text;

  const ToolsType(this.text);
}

class ToolsBottomSheet extends StatefulWidget {
  ToolsBottomSheet({super.key});

  @override
  State<ToolsBottomSheet> createState() => _ToolsBottomSheetState();
}

class _ToolsBottomSheetState extends State<ToolsBottomSheet> with SingleTickerProviderStateMixin{
  late TabController _tabController;

  Rx<ToolsType> currentType = ToolsType.bookmark.obs;

  RxString searchText = ''.obs;

  FocusNode searchHistoryFocusNode = FocusNode();

  TextEditingController searchHistoryController = TextEditingController();

  List<WebBookmarkModel> get starUrls => HiveHelper.instance.getAllStarWebUrl();

  List<WebBookmarkModel> get historyUrls => HiveHelper.instance.getAllWebHistory();

  List<String> get customHomepageUrls => HiveHelper.instance.getAllCustomHomepageUrl();

  String get homePageUrl => HiveHelper.instance.webHomePageUrl;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: ToolsType.values.length, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();
    searchHistoryFocusNode.dispose();
    searchHistoryController.dispose();
    super.dispose();
  }

  void back({bool alwaysBack = false}) {
    if (!alwaysBack && searchHistoryFocusNode.hasFocus) {
      searchHistoryFocusNode.unfocus();
      return;
    }
    Get.back();
  }

  void openUrl(String url) {
    if (Get.isRegistered<BrowserLogic>()) {
      var logic = Get.find<BrowserLogic>();
      logic.loadWeb(url: url);
      back(alwaysBack: true);
    }
  }

  Future<void> onEditBookmark(WebBookmarkModel model) async {
    await Get.dialog(
      EditBookmarkDialog(model: model,),
      barrierDismissible: false,
      useSafeArea: false,
    );
    setState(() {});
  }

  Future<void> deleteHistory(WebBookmarkModel model) async {
    searchHistoryFocusNode.unfocus();
    Get.dialog(
      defaultDialog(
          title: '删除该记录',
          content: model.url,
          sureFunction: () {
            HiveHelper.instance.deleteWebHistory(model);
            setState(() {});
          }
      ),
      barrierDismissible: false,
      useSafeArea: false,
    );
  }

  void deleteAllHistory() async {
    searchHistoryFocusNode.unfocus();
    Get.dialog(
      defaultDialog(
          title: '删除全部记录',
          content: '共 ${historyUrls.length} 条',
          sureFunction: () {
            HiveHelper.instance.deleteAllWebHistory();
            HiveHelper.instance.cleanFetchWebsiteInfo();
            setState(() {});
          }
      ),
      useSafeArea: false,
    );
  }

  void onTapSelectHomePage(String url) {
    HiveHelper.instance.webHomePageUrl = url;
    setState(() {});
  }

  Future<void> onAddHomePage() async {
    await Get.dialog(AddHomepageUrlDialog());
    setState(() {});
  }

  void editCustomHistory(String url) async {
    await Get.dialog(
      AddHomepageUrlDialog(url: url,),
    );
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: back,
        child: DraggableScrollableSheet(
          initialChildSize: 0.5,
          minChildSize: 0.5,
          maxChildSize: 0.85,
          snap: true,
          shouldCloseOnMinExtent: false,
          builder: (BuildContext context, ScrollController scrollController) {
            return Stack(
              children: [
                GestureDetector(
                  onTap: () {
                    if (searchHistoryFocusNode.hasFocus) {
                      searchHistoryFocusNode.unfocus();
                      return;
                    }
                  },
                  child: Container(
                    decoration: const BoxDecoration(
                      color: Styles.lightColor,
                      borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
                    ),
                    child: Column(
                      children:[
                        const SizedBox(height: 20),
                        Obx(() => Text(
                          currentType.value.text,
                          style: Styles.textStyle(size: 20, height: 1.2).copyWith(fontWeight: FontWeight.w800),
                        )),
                        const SizedBox(height: 16),
                        Container(
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(8),
                            color: Colors.grey.shade200,
                          ),
                          margin: const EdgeInsets.symmetric(horizontal: 20),
                          padding: const EdgeInsets.fromLTRB(2, 2, 2, 2),
                          child: TabBar(
                            controller: _tabController,
                            onTap: (index) {
                              searchHistoryFocusNode.unfocus();
                              _tabController.animateTo(index);
                              currentType.value = ToolsType.values[index];
                            },
                            tabs: [
                              ...List.generate(ToolsType.values.length, (index) => tabItem(ToolsType.values[index]))
                            ],
                            indicator: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(8),
                              boxShadow: [BoxShadow(color: Colors.black.withOpacity(.1), offset: const Offset(1, 2), blurRadius: 4)]
                            ),
                            indicatorSize: TabBarIndicatorSize.tab,
                          ),
                        ),
                        const SizedBox(height: 10),
                        Expanded(
                          child: Scrollbar(
                            controller: scrollController,
                            child: SingleChildScrollView(
                              controller: scrollController,
                              child: Obx(() {
                                switch(currentType.value) {
                                  case ToolsType.bookmark:
                                    return bookmarkView();
                                  case ToolsType.homePage:
                                    return homePageSetView();
                                  case ToolsType.history:
                                    return historyView();
                                }
                              }),
                            ),
                          )
                        ),
                      ],
                    ),
                  ),
                ),
                Positioned(
                  right: 0,
                  top: 5,
                  child: TextButton(
                    onPressed: () => back(alwaysBack: true),
                    child: Text(
                      '关闭',
                      style: Styles.textStyle(size: 16, color: Colors.blue).copyWith(fontWeight: FontWeight.w600),
                    ),
                  ),
                ),
                Positioned(
                  left: 5,
                  top: 5,
                  child: Obx(() {
                    switch(currentType.value){
                      case ToolsType.bookmark:
                        return const SizedBox();
                      case ToolsType.homePage:
                        return TextButton(
                          onPressed: onAddHomePage,
                          child: Text(
                            '添加',
                            style: Styles.textStyle(size: 16, color: Colors.blue).copyWith(fontWeight: FontWeight.w600),
                          ),
                        );
                      case ToolsType.history:
                        return TextButton(
                          onPressed: deleteAllHistory,
                          child: Text(
                            '全部删除',
                            style: Styles.textStyle(size: 16, color: Colors.blue).copyWith(fontWeight: FontWeight.w600),
                          ),
                        );
                    }
                  }),
                ),
              ],
            );
          },
        ),
      ),
    );
  }

  Widget tabItem(ToolsType type){
    IconData? icon;
    switch(type){
      case ToolsType.bookmark:
        icon = Icons.bookmark_border_outlined;
      case ToolsType.homePage:
        icon = Icons.home_outlined;
      case ToolsType.history:
        icon = Icons.history;
    }
    return Padding(
      padding: const EdgeInsets.all(4),
      child: Icon(icon),
    );
  }

  Widget bookmarkItem(WebBookmarkModel model) {
    FetchWebsiteInfoModel? fetch = HiveHelper.instance.findWebsiteInfoFetchByUrl(model.url);
    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: () => openUrl(model.url),
        onLongPress: () => onEditBookmark(model),
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 30),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const SizedBox(height: 15),
              Row(
                children: [
                  Padding(
                    padding: const EdgeInsets.only(right: 8),
                    child: Image.network(
                      fetch?.image ?? "",
                      width: 20,
                      height: 20,
                      errorBuilder: (_, __, ___) {
                        return const Icon(Icons.web, size: 30);
                      },
                    ),
                  ),
                  Expanded(
                    child: Text(
                      model.name,
                      style: Styles.textStyle(size: 16),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 15),
              Container(
                width: double.infinity,
                height: 0.5,
                color: Colors.grey,
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget bookmarkView() {
    return Column(
      children: [
        ...List.generate(starUrls.length,(index) => bookmarkItem(starUrls[index])),
      ],
    );
  }

  Widget homePageSetView() {
    Widget item(String url){
      bool selected = url == homePageUrl;
      return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () => onTapSelectHomePage(url),
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 15),
          color: selected ? Colors.blue.shade200 : null,
          child: Row(
            children: [
              Expanded(
                child: Text(
                  url,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: Styles.textStyle(size: 16),
                ),
              ),
            ],
          ),
        ),
      );
    }
    return Column(
      children:[
        item(bingUrl),
        item(baiduUrl),
        item(googleUrl),
        ...List.generate(customHomepageUrls.length, (index) => Material(
          child: InkWell(
            onLongPress: () => editCustomHistory(customHomepageUrls[index]),
            child: item(customHomepageUrls[index]),
          ),
        ))
      ],
    );
  }

  Widget historyView() {
    bool equalByDay(DateTime? a, DateTime? b){
      if (a == null || b == null) {
        return true;
      }
      return a.year == b.year && a.month == b.month && a.day == b.day;
    }

    Widget item(WebBookmarkModel model, {bool showTimeTitle = false}) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          showTimeTitle ? Container(
            margin: const EdgeInsets.only(left: 20, top: 10),
            padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 4),
            decoration: BoxDecoration(
              color: Colors.grey.shade200,
              borderRadius: BorderRadius.circular(8)
            ),
            child: Text(model.time != null ? DateFormat('yyyy-MM-dd').format(model.time!) : 'Null'),
          ) : const SizedBox(),
          Material(
            color: Colors.transparent,
            child: InkWell(
              onTap: () => openUrl(model.url),
              onLongPress: () => deleteHistory(model),
              child: Container(
                padding: const EdgeInsets.only(left: 10, right: 10),
                child: Column(
                  children: [
                    SizedBox(
                      height: 60,
                      child: Builder(
                        builder: (context) {
                          FetchWebsiteInfoModel? fetch = HiveHelper.instance.findWebsiteInfoFetchByUrl(model.url);
                          return Row(
                              children:[
                                Padding(
                                  padding: const EdgeInsets.all(8.0),
                                  child: Image.network(
                                    fetch?.image ?? '',
                                    height: 30,
                                    width: 30,
                                    fit: BoxFit.fill,
                                    errorBuilder: (_, __, ___) {
                                      return const Icon(Icons.web, size: 30);
                                    },
                                  ),
                                ),
                                Expanded(
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        fetch?.title ?? model.url,
                                        maxLines: 1,
                                        overflow: TextOverflow.ellipsis,
                                        style: Styles.textStyle(size: 16),
                                      ),
                                      const SizedBox(height: 4),
                                      Text(
                                        model.url,
                                        maxLines: 1,
                                        overflow: TextOverflow.ellipsis,
                                        style: Styles.textStyle(size: 12, color: Styles.textTranslucentColor),
                                      ),
                                      const SizedBox(height: 4),
                                      Text(
                                        model.time != null ? DateFormat('yyyy-MM-dd HH:mm:ss').format(model.time!) : 'Null',
                                        maxLines: 1,
                                        overflow: TextOverflow.ellipsis,
                                        style: Styles.textStyle(size: 12, color: Styles.textTranslucentColor),
                                      ),
                                    ],
                                  ),
                                )
                              ]
                          );
                        }
                      ),
                    ),
                    Container(
                      width: double.infinity,
                      height: 0.5,
                      color: Colors.grey,
                      margin: const EdgeInsets.only(right: 20, left: 20),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      );
    }

    return Column(
      children: [
        Container(
          decoration: BoxDecoration(
            color: Colors.grey.shade200,
          ),
          child: Row(
            children: [
              const SizedBox(width: 20),
              const Icon(
                Icons.search,
                color: Colors.grey,
              ),
              Expanded(
                child: TextFormField(
                  controller: searchHistoryController,
                  focusNode: searchHistoryFocusNode,
                  decoration: InputDecoration(
                    hintText: '搜索历史记录',
                    border: InputBorder.none,
                    hintStyle: Styles.textStyle(color: Colors.grey),
                    contentPadding: const EdgeInsets.only(left: 10),
                  ),
                  style: Styles.textStyle(),
                  maxLines: 1,
                  onChanged: (text) {
                    searchText.value = text;
                  },
                ),
              ),
              Obx(() {
                return searchText.value.isEmpty ? const SizedBox() : IconButton(
                  onPressed: () {
                    searchHistoryController.clear();
                    searchText.value = '';
                  },
                  icon: const Icon(
                    Icons.clear,
                    color: Colors.grey,
                  ),
                );
              }),
              const SizedBox(width: 5),
            ],
          ),
        ),
        const SizedBox(height: 5),
        Obx(() {
          var list = historyUrls;
          if (searchText.isNotEmpty) {
            list = historyUrls.where((e) => e.url.contains(searchText.value) || e.name.contains(searchText.value)).toList();
          }
          return Column(
            children:[
              ...List.generate(list.length, (index) {
                bool showTimeTitle = false;
                if (index == 0) {
                  showTimeTitle = true;
                } else {
                  showTimeTitle = !equalByDay(list[index].time, list[index - 1].time);
                }
                return item(list[index], showTimeTitle: showTimeTitle);
              }),
            ],
          );
        }),
        SizedBox(height: 40 + SizeConfig.bottomMargin),
      ],
    );
  }
}
